<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="企业名称：">
            <cascaderDom ref="childOrg" @setOrgInfo="setOrgId" @setOrgname="setOrgName"
                         :orgTree="true" :root-org-id="companyId"></cascaderDom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="活动日期：">
            <!--  <DatePicker type="year" v-model="form1.yearDate" style="width: 100%"></DatePicker>-->
            <DatePicker type="daterange" split-panels v-model="date" style="width: 100%"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8">
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="queryAll()">查询</Button>
        </Col>
      </Row>
    </Form>
    <Row style="margin-right:10px; margin-top: 5px;">
      <Col span="24">
        <Card dis-hover>
          <div ref="activityStat" style="height: 300px;"></div>
        </Card>
      </Col>
    </Row>
    <Row class="query-form">
      <Col span="24">
        <Button size="large" :disabled="type === '1'" class="ivu-btn-add" icon="md-home" @click="back">返回</Button>
      </Col>
    </Row>
    <Table ref='table' :loading="loading" size="small" :height="300" class="no-add-table"
           no-data-text="没有查询到相关数据!"
           highlight-row stripe border :columns="columns" width="100%" :data="dataTable">
    </Table>


  </Layout>
</template>

<script>
import {Api} from '../../../../api/index.js'
import {sessionStorage} from '../../../../common/cacheUtils.js';
import cascaderDom from '../../../../components/cascader-dom.vue';
import echarts from "echarts";

export default {
  components: {cascaderDom},
  name: "riskStatical",
  data() {
    return {
      date: ['', ''],
      loading: false, tableHeight: '',
      form1: {
        orgId: '',
        year: '',
        yearDate: ''
      },
      twoOrgId: '',
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      type: '1',
      companyId: sessionStorage('userId').getObject('userId').companyId,
      dataTable: [],
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          minWidth: 200,
          title: '单位名称',
          fixed: 'left',
          align: 'center',
          key: 'orgName',
        },
        {
          minWidth: 100,
          title: '活动方案数量',
          align: 'center',
          key: 'programmeCount',
          render: (h, params) => {
            return h('span', params.row.programmeCount || 0)
          }
        },
        {
          minWidth: 100,
          title: '活动信息数量',
          align: 'center',
          key: 'activitysCount',
          render: (h, params) => {
            return h('span', params.row.activitysCount || 0)
          }
        },
        {
          minWidth: 150,
          title: '活动作品数量',
          align: 'center',
          children: [
            {
              title: '图片',
              key: 'imgCount',
              align: 'center',
              minWidth: 100,
              render: (h, params) => {
                return h('span', params.row.imgCount || 0)
              }
            }, {
              title: '视频',
              key: 'videoCount',
              align: 'center',
              minWidth: 100,
              render: (h, params) => {
                return h('span', params.row.videoCount || 0)
              }
            },
          ]
        },

      ],
      twoOrgMap: {},
      model1: false,
      model2: false,
      buttonDisabled: false,
      container: null,
      InputData: {},
    }
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 103;
    this.container = echarts.init(this.$refs.activityStat);
    this.queryTwoOrgList();
    this.query()
    this.activityStatQuery();

  },
  computed: {
    columns() {
      let column = {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 140,
        align: 'center',
        render: (h, params) => {
          if (params.row.orgId === '18000000') {
            return;
          }
          return h('div', [
            h('A', {
              props: {
                type: 'primary',
                size: 'small'
              },
              style: {
                fontSize: '12px',
              },
              on: {
                click: () => {
                  this.type = '2';
                  this.twoOrgId = params.row.orgId;
                  this.query();
                }
              }
            }, '详情'),
          ]);
        }
      }
      if (this.type === '1') {
        return [
          ...this.columns1,
          column
        ]
      } else {
        return [
          ...this.columns1,
        ]
      }
    },

  },
  methods: {
    getOption(data) {
      let orgNames = [];
      let imgCount = [];
      let videoCount = [];
      let programmeCount = [];
      let activitysCount = [];
      data.forEach(item => {
        orgNames.push(item['orgName']);
        imgCount.push(item['imgCount']);
        videoCount.push(item['videoCount']);
        programmeCount.push(item['programmeCount']);
        activitysCount.push(item['activitysCount']);
      })

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        legend: {
          data: ['活动方案数量', '活动信息数量', '活动作品图片数量', '活动作品视频数量']
        },

        xAxis: [
          {
            type: 'category',
            axisTick: {show: false},
            data: orgNames,
            axisLabel: {
              show: true,
              interval: 0,
              formatter: function (params) {
                var newParamsName = "";
                var paramsNameNumber = params.length;
                var provideNumber = 4; // 一行显示几个字 然后就超过字数就会自动换行
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                if (paramsNameNumber > provideNumber) {
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = "";
                    var start = p * provideNumber;
                    var end = start + provideNumber;
                    if (p == rowNumber - 1) {
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr;
                  }
                } else {
                  newParamsName = params;
                }
                return newParamsName;
              },
            },
          }
        ],
        yAxis: [
          {
            type: 'value',
          },
        ],
        color: ['#42A5F5', '#FFC310', '#4CD1A8', '#FD5C50'],
        series: [
          {
            name: '活动方案数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: programmeCount,

          },
          {
            name: '活动信息数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: activitysCount,
          },
          {
            name: '活动作品图片数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: imgCount,
          },
          {
            name: '活动作品视频数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: videoCount,
          },

        ]
      }
    },
    queryCompany(name) {
      if (name === '总部') return;
      let _this = this;
      if (this.date[0] != "" && this.date[1] != "") {
        this.form1.startDate = this.formatDate(new Date(this.date[0]), 'yyyy-MM-dd');
        this.form1.endDate = this.formatDate(new Date(this.date[1]), 'yyyy-MM-dd');
      }
      let orgId = sessionStorage('userId').getObject('userId').companyId
      let data = {...this.form1, orgId}
      data['twoLevelOrgId'] = this.twoOrgMap[name];
      this.$http.get(Api.activityStat + '2', {params: data}).then(res => {
        if (res.data.status === 200) {
          this.setCompanyOption(res.data.data);
        } else {
          this.$Message.error(res.data.msg);
        }
      }).catch(e => {
        console.log(e)
        this.$Message.error("查询失败")
      });
    },
    activityStatQuery() {
      let _this = this;
      if (this.date[0] != "" && this.date[1] != "") {
        this.form1.startDate = this.formatDate(new Date(this.date[0]), 'yyyy-MM-dd');
        this.form1.endDate = this.formatDate(new Date(this.date[1]), 'yyyy-MM-dd');
      }
      let orgId = sessionStorage('userId').getObject('userId').companyId
      let data = {...this.form1, orgId}
      this.$http.get(Api.activityStat + '1', {params: data}).then(res => {
        if (res.data.status === 200) {
          this.activityInit(res.data.data);
        } else {
          this.$Message.error(res.data.msg);
        }
      }).catch(e => {
        console.log(e)
        this.$Message.error("查询失败")
      });
    },
    back() {
      this.type = '1';
      this.twoOrgId = '';
      this.query();
    },
    setOrgId(data) {
      this.form1.orgId = data[data.length - 1];
    },
    setOrgName(data) {
      this.form1.orgName = data;
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    queryAll() {
      this.query();
      this.activityStatQuery();

    },
    queryTwoOrgList() {
      this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
        res.data.data.forEach(item => {
          this.twoOrgMap[item['orgName']] = item['orgId']
        });
      })
    },
    setCompanyOption(data) {
      this.container?.clear();
      this.container?.off('click');
      let option = this.getCompanyOption(data);
      this.container.setOption(option);
      window.onresize = this.container.resize;
    },
    getCompanyOption(data) {
      let orgNames = [];
      let imgCount = [];
      let videoCount = [];
      let programmeCount = [];
      let activitysCount = [];
      data.forEach(item => {
        orgNames.push(item['orgName']);
        imgCount.push(item['imgCount']);
        videoCount.push(item['videoCount']);
        programmeCount.push(item['programmeCount']);
        activitysCount.push(item['activitysCount']);
      })

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        toolbox: {
          show: true,//是否显示工具栏组件
          right: 20, // toolbox的定位位置
          top: -5,
          feature: {
            myTool1: {
              show: true,
              title: '返回',
              icon: "path://M853.333333 245.333333H245.333333l93.866667-93.866666c12.8-12.8 12.8-34.133333 0-46.933334-12.8-12.8-34.133333-12.8-46.933333 0l-145.066667 145.066667c-12.8 12.8-12.8 34.133333 0 46.933333l145.066667 145.066667c6.4 6.4 14.933333 10.666667 23.466666 10.666667s17.066667-4.266667 23.466667-10.666667c12.8-12.8 12.8-34.133333 0-46.933333L256 311.466667h597.333333c6.4 0 10.666667 4.266667 10.666667 10.666666v426.666667c0 6.4-4.266667 10.666667-10.666667 10.666667H170.666667c-17.066667 0-32 14.933333-32 32s14.933333 32 32 32h682.666666c40.533333 0 74.666667-34.133333 74.666667-74.666667V320c0-40.533333-34.133333-74.666667-74.666667-74.666667z",
              onclick: () => {
                this.activityStatQuery();
              }
            }
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        dataZoom: [{
          type: 'inside',
          zoomOnMouseWheel: false,
          start: 0,
          end: 10,
        }, {
          type: 'slider',
          textStyle: false
        }],
        legend: {
          data: ['活动方案数量', '活动信息数量', '活动作品图片数量', '活动作品视频数量']
        },

        xAxis: [
          {
            type: 'category',
            axisTick: {show: false},
            data: orgNames,
            axisLabel: {
              show: true,
              interval: 0,
              formatter: function (params) {
                var newParamsName = "";
                var paramsNameNumber = params.length;
                var provideNumber = 4; // 一行显示几个字 然后就超过字数就会自动换行
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                if (paramsNameNumber > provideNumber) {
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = "";
                    var start = p * provideNumber;
                    var end = start + provideNumber;
                    if (p == rowNumber - 1) {
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr;
                  }
                } else {
                  newParamsName = params;
                }
                return newParamsName;
              },
            },
          }
        ],
        yAxis: [
          {
            type: 'value',
          },
        ],
        color: ['#42A5F5', '#FFC310', '#4CD1A8', '#FD5C50'],
        series: [
          {
            name: '活动方案数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: programmeCount,

          },
          {
            name: '活动信息数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: activitysCount,
          },
          {
            name: '活动作品图片数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: imgCount,
          },
          {
            name: '活动作品视频数量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: videoCount,
          },

        ]
      }
    },
    activityInit(data) {
      this.container?.clear();
      this.container?.off('click');
      let option = this.getOption(data);
      this.container.setOption(option);
      this.container.on("click", this.onSelect);
      window.onresize = this.container.resize;
    },
    onSelect(param) {
      event.stopPropagation() // 阻止冒泡
      this.queryCompany(param.name);
    },
    query() {
      this.loading = true;
      if (this.date[0] != "" && this.date[1] != "") {
        this.form1.startDate = this.formatDate(new Date(this.date[0]), 'yyyy-MM-dd');
        this.form1.endDate = this.formatDate(new Date(this.date[1]), 'yyyy-MM-dd');
      }
      if (this.form1.orgId == "") {
        this.form1.orgId = sessionStorage('userId').getObject('userId').companyId
      }
      this.form1.year = new Date(this.form1.yearDate).getFullYear()
      let data = {...this.form1};
      if (this.twoOrgId) data.twoLevelOrgId = this.twoOrgId;
      let url = Api.activityStat
      this.$http.get(url + this.type, {params: data}).then((res) => {
        this.dataTable = res.data.data;
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    reset() {
      this.form1 = {
        orgId: '',
        year: '',
        yearDate: ''
      }
      this.date = ['', ''];
      this.$refs.childOrg.resetCurrentOrg();
      this.query();
      this.activityStatQuery();
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
  }
}
</script>

<style scoped>
@import '../../../../index.css';
</style>
